const styles = require('./video.css').default

interface Ivideo {
  url: string;
  el: string | HTMLElement;
  width?: string;
  height?: string;
  autoplay?: boolean;
}

interface Icomponent {
  tempContainer: HTMLElement;
  init: () => void;
  template: () => void;
  handle: () => void;
}

export default function video (options: Ivideo) {
  return new Video(options)
}

function formatTime (t: number): string {
  t = Math.round(t);
  const min = Math.floor(t / 60)
  const sec = t % 60;
  return `${setZero(min)}:${setZero(sec)}`;
}

function setZero (n: number): string | number {
  if (n < 10) {
    return '0' + n
  }
  return n
}

class Video implements Icomponent {
  tempContainer: HTMLElement;
  constructor (private settings: Ivideo) {
    this.settings = {
      width: '100%',
      height: '100%',
      autoplay: false,
      ...this.settings
    }
    this.init()
  }
  init () {
    this.template()
    this.handle()
  }
  template () {
    if (typeof this.settings.el === 'string') {
      this.settings.el = document.querySelector(this.settings.el) as HTMLElement
    } else if (!this.settings.el) {
      throw new Error('必须指定播放器挂载目标')
    }
    this.tempContainer = document.createElement('div')
    this.tempContainer.classList.add(styles.video)
    this.tempContainer.style.width = this.settings.width;
    this.tempContainer.style.height = this.settings.height
    this.tempContainer.innerHTML = `
      <video class="${styles['video-content']}" src="${this.settings.url}" autoplay="${this.settings.autoplay}"></video>
      <div class="${styles['video-controls']}">
        <div class="${styles['video-progress']}">
          <div class="${styles['video-progress-now']}"></div>
          <div class="${styles['video-progress-suc']}"></div>
          <div class="${styles['video-progress-bar']}"></div>
        </div>
        <div class="${styles['video-play']}">
          <i class="icon-play"></i>
        </div>
        <div class="${styles['video-time']}">
          <span>00:00</span> / <span>00:00</span>
        </div>
        <div class="${styles['video-fullscreen']}">
          <i class="icon-fullscreen"></i>
        </div>
        <div class="${styles['video-volume']}">
          <i class="icon-volume-medium"></i>
          <div class="${styles['video-volprogress']}">
            <div class="${styles['video-volprogress-now']}"></div>
            <div class="${styles['video-volprogress-bar']}"></div>
          </div>
        </div>
      </div>
    `
    // <div class="${styles['video-volprogress-suc']}"></div>
    this.settings.el.appendChild(this.tempContainer)
    console.log('templated')
  }
  handle () {
    const videoContent: HTMLVideoElement = this.tempContainer.querySelector(`.${styles['video-content']}`)
    const videoControls = this.tempContainer.querySelector(`.${styles['video-controls']}`)
    const videoProgress: NodeListOf<HTMLElement> = this.tempContainer.querySelectorAll(`.${styles['video-progress']} div`)
    const videoVolProgress: NodeListOf<HTMLElement> = this.tempContainer.querySelectorAll(`.${styles['video-volprogress']} div`)
    const videoPlayBtn = this.tempContainer.querySelector(`.${styles['video-controls']} i`)
    const videoTimes = this.tempContainer.querySelectorAll(`.${styles['video-time']} span`)
    let timer
    const videoFullscreenBtn = this.tempContainer.querySelector(`.${styles['video-fullscreen']} i`)

    videoContent.volume = 0.5

    videoContent.addEventListener('canplay', () => {
      console.log('canplay')
      videoTimes[1].innerHTML = formatTime(videoContent.duration)
    })

    videoContent.addEventListener('play', () => {
      videoPlayBtn.className = 'icon-pause'
      timer = setInterval(playing, 999)
    })

    videoContent.addEventListener('pause', () => {
      videoPlayBtn.className = 'icon-play'
    })

    videoPlayBtn.addEventListener('click', () => {
      if (videoContent.paused) {
        videoContent.play()
      } else {
        videoContent.pause()
      }
    })

    videoFullscreenBtn.addEventListener('click', () => {
      videoContent.requestFullscreen()
    })

    videoProgress[2].addEventListener('mousedown', function (evt) {
      const x = evt.pageX
      const left = this.offsetLeft
      document.onmousemove = (evt2) => {
        let pct = (evt2.pageX - x + left + 8) / this.parentElement.offsetWidth
        if (pct < 0) {
          pct = 0
        } else if (pct > 1) {
          pct = 1
        }
        videoProgress[0].style.width = pct * 100 + '%'
        videoProgress[1].style.width = pct * 100 + '%'
        this.style.left = pct * 100 + '%'
        videoContent.currentTime = pct * videoContent.duration
      }
      document.onmouseup = () => {
        document.onmousemove = document.onmouseup = null;
      }
      evt.preventDefault();
    })

    videoVolProgress[1].addEventListener('mousedown', function (evt) {
      const x = evt.pageX
      const left = this.offsetLeft
      document.onmousemove = (evt2) => {
        let pct = (evt2.pageX - x + left + 8) / this.parentElement.offsetWidth
        if (pct < 0) {
          pct = 0
        } else if (pct > 1) {
          pct = 1
        }
        videoVolProgress[0].style.width = pct * 100 + '%'
        this.style.left = pct * 100 + '%'
        videoContent.volume = pct;
      }
      document.onmouseup = () => {
        document.onmousemove = document.onmouseup = null;
      }
      evt.preventDefault();
    })

    function playing () {
      let progressPercent = videoContent.currentTime / videoContent.duration
      let bufferPercent = videoContent.buffered.end(0) / videoContent.duration;
      videoTimes[0].innerHTML = formatTime(videoContent.currentTime);
      videoProgress[0].style.width = progressPercent * 100 + '%'
      videoProgress[1].style.width = bufferPercent * 100 + '%'
      videoProgress[2].style.left = progressPercent * 100 + '%'
    }
  }
}